﻿using System;
using System.Collections;
using UnityEngine;


public class NetProxy : MonoBehaviour
{
    
    private static NetProxy instance = null;
    public static NetProxy GetInst()
    {
        return instance;
    }

    void Awake()
    {
        instance = this;
    }



    public delegate void CallBackCommon(bool success);
    public delegate void CallBackInfo(bool success, string info);



    // 登陆成功后，带cookie的发送消息
    public WWW Send(string url, WWWForm form = null,string cookie = null )
    {
        if (string.IsNullOrEmpty(url))
        {
            Debug.Log("url is null, can't send message");
            return null;
        }

        if (form != null)
        {
            var headers = form.headers;

            if ( string.IsNullOrEmpty( cookie )  == false )
                headers["Cookie"] = cookie;

            foreach (var item in headers)
            {
                Debug.Log(item.Key + " : " + item.Value);
            }

            var datas = form.data;

            return new WWW(url, datas, headers);
        }
        else
        {
            return new WWW(url);
        }
    }


    // 获取返回数据
    public void ReqText( string url, WWWForm form =null, CallBackInfo callback = null, string cookie = null )
    {
        StartCoroutine(ReqTextDo(url, form, callback, cookie));
    }

    IEnumerator ReqTextDo(string url, WWWForm form, CallBackInfo callback, string cookie )
    {
        WWW www = Send(url, form, cookie);

        yield return www;

        if (string.IsNullOrEmpty(www.error) == false)
        {
            Debug.LogError(www.error);

            if (callback != null)
            {
                callback(false, null);
            }

        }
        else
        {
            Debug.Log(www.text);

            if (callback != null)
            {
                callback(true, www.text);
            }
        }
    }






}

